﻿using LunarSF.SHomeWorkshop.LunarMarkdownEditor.Widgets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    class EditorPopupToolBar : Popup
    {
        public EditorPopupToolBar(MarkdownEditorBase editorBase)
        {
            this.AllowsTransparency = true;
            this.PopupAnimation = PopupAnimation.Scroll;
            this.StaysOpen = false;
            this.Placement = PlacementMode.Mouse;

            this.masterEditorBase = editorBase;

            System.Windows.Style btnStyle = new System.Windows.Style();
            var btnBackgroundTrigger = new System.Windows.Trigger()
            {
                Property = IsMouseOverProperty,
                Value = true,
            };
            btnBackgroundTrigger.Setters.Add(new System.Windows.Setter()
            {
                Property = Border.BackgroundProperty,
                Value = L.ThemeBrown,
            });
            btnStyle.Triggers.Add(btnBackgroundTrigger);

            baseGrid = new Grid()
            {
                Margin = new System.Windows.Thickness(1),
            };

            // 用来处理试题解析的放在最上行，反正平时也不显示。
            questionToolsRowDefinition = new RowDefinition()
            {
                Height = new System.Windows.GridLength(0, System.Windows.GridUnitType.Pixel),
            };
            baseGrid.RowDefinitions.Add(questionToolsRowDefinition);
            baseGrid.RowDefinitions.Add(new RowDefinition());
            baseGrid.RowDefinitions.Add(new RowDefinition());
            baseGrid.RowDefinitions.Add(new RowDefinition());

            baseGrid.ColumnDefinitions.Add(new ColumnDefinition());
            baseGrid.ColumnDefinitions.Add(new ColumnDefinition());
            baseGrid.ColumnDefinitions.Add(new ColumnDefinition());
            baseGrid.ColumnDefinitions.Add(new ColumnDefinition());
            baseGrid.ColumnDefinitions.Add(new ColumnDefinition());
            baseGrid.ColumnDefinitions.Add(new ColumnDefinition());
            baseGrid.ColumnDefinitions.Add(new ColumnDefinition());

            // 第2行按钮（第1行是试题专用，平时隐藏）

            Border btnCut = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "Ctrl+X，剪切文本",
            };
            btnCut.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/CutHS.png")),
            };
            btnCut.MouseLeftButtonDown += BtnCut_MouseLeftButtonDown;
            baseGrid.Children.Add(btnCut);
            Grid.SetColumn(btnCut, 0);
            Grid.SetRow(btnCut, 1);

            Border btnCopy = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "Ctrl+C，复制文本",
            };
            btnCopy.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/CopyHS.png")),
            };
            btnCopy.MouseLeftButtonDown += BtnCopy_MouseLeftButtonDown;
            baseGrid.Children.Add(btnCopy);
            Grid.SetColumn(btnCopy, 1);
            Grid.SetRow(btnCopy, 1);

            Border btnPaste = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "Ctrl+V，粘贴文本",
            };
            btnPaste.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/PasteHS.png")),
            };
            btnPaste.MouseLeftButtonDown += BtnPaster_MouseLeftButtonDown;
            baseGrid.Children.Add(btnPaste);
            Grid.SetColumn(btnPaste, 2);
            Grid.SetRow(btnPaste, 1);

            Border btnBold = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "Ctrl+B，切换加粗，不支持跨行",
            };
            btnBold.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/format-text-bold-5.png")),
            };
            btnBold.MouseLeftButtonDown += BtnBold_MouseLeftButtonDown;
            baseGrid.Children.Add(btnBold);
            Grid.SetColumn(btnBold, 3);
            Grid.SetRow(btnBold, 1);

            Border btnItalic = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "Ctrl+I，切换倾斜，不支持跨行",
            };
            btnItalic.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/format-text-italic-5.png")),
            };
            btnItalic.MouseLeftButtonDown += BtnItalic_MouseLeftButtonDown;
            baseGrid.Children.Add(btnItalic);
            Grid.SetColumn(btnItalic, 4);
            Grid.SetRow(btnItalic, 1);

            Border btnHaiCi = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "调用海词（dict.cn）搜索选定的单词",
            };
            btnHaiCi.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/HaiCi.png")),
            };
            btnHaiCi.MouseLeftButtonDown += BtnHaiCi_MouseLeftButtonDown;
            baseGrid.Children.Add(btnHaiCi);
            Grid.SetRow(btnHaiCi, 1);
            Grid.SetColumn(btnHaiCi, 5);

            Border btnBaidu = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "调用百度搜索选定的文本",
            };
            btnBaidu.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/baidu.png")),
            };
            btnBaidu.MouseLeftButtonDown += BtnBaidu_MouseLeftButtonDown;
            baseGrid.Children.Add(btnBaidu);
            Grid.SetRow(btnBaidu, 1);
            Grid.SetColumn(btnBaidu, 6);

            // 第3行按钮

            Border btnJoinParagraphs = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "向下合并段落",
            };
            btnJoinParagraphs.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/Line-join-color.png")),
            };
            btnJoinParagraphs.MouseLeftButtonDown += BtnJoinParagraphs_MouseLeftButtonDown;
            baseGrid.Children.Add(btnJoinParagraphs);
            Grid.SetColumn(btnJoinParagraphs, 0);
            Grid.SetRow(btnJoinParagraphs, 2);

            Border btnCodeSpinnet = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "Ctrl+`，切换代码片段标记（一对反引号），不支持跨行",
            };
            btnCodeSpinnet.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/codespinnet.png")),
            };
            btnCodeSpinnet.MouseLeftButtonDown += BtnCodeSpinnet_MouseLeftButtonDown; ;
            baseGrid.Children.Add(btnCodeSpinnet);
            Grid.SetRow(btnCodeSpinnet, 2);
            Grid.SetColumn(btnCodeSpinnet, 1);

            Border btnUnOrderedList = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "选定行添加无序列表标记，支持跨行",
            };
            btnUnOrderedList.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/format-list-unordered.png")),
            };
            btnUnOrderedList.MouseLeftButtonDown += BtnUnorderedList_MouseLeftButtonDown;
            baseGrid.Children.Add(btnUnOrderedList);
            Grid.SetRow(btnUnOrderedList, 2);
            Grid.SetColumn(btnUnOrderedList, 2);

            Border btnAddBlockQuoteMark = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "选定行添加引用块标记，支持跨行",
            };
            btnAddBlockQuoteMark.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/AddBlockQuoterMark.png")),
            };
            btnAddBlockQuoteMark.MouseLeftButtonDown += BtnAddBlockQuoteMark_MouseLeftButtonDown;
            baseGrid.Children.Add(btnAddBlockQuoteMark);
            Grid.SetRow(btnAddBlockQuoteMark, 2);
            Grid.SetColumn(btnAddBlockQuoteMark, 3);

            Border btnAddRegionMark = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "选定行添加 region {...} 标记，支持跨行",
            };
            btnAddRegionMark.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/brackets.png")),
            };
            btnAddRegionMark.MouseLeftButtonDown += BtnAddRegionMark_MouseLeftButtonDown;
            baseGrid.Children.Add(btnAddRegionMark);
            Grid.SetRow(btnAddRegionMark, 2);
            Grid.SetColumn(btnAddRegionMark, 4);

            Border btnAddSquareMark = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "选定行添加 [...] 标记，支持跨行",
            };
            btnAddSquareMark.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/square-brackets.png")),
            };
            btnAddSquareMark.MouseLeftButtonDown += BtnAddSquareMark_MouseLeftButtonDown; ;
            baseGrid.Children.Add(btnAddSquareMark);
            Grid.SetRow(btnAddSquareMark, 2);
            Grid.SetColumn(btnAddSquareMark, 5);

            Border btnPreviewSegment = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "预览选定行编译为Html的效果",
            };
            btnPreviewSegment.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/preview-segment.png")),
            };
            btnPreviewSegment.MouseLeftButtonDown += BtnPreviewSegment_MouseLeftButtonDown; ;
            baseGrid.Children.Add(btnPreviewSegment);
            Grid.SetRow(btnPreviewSegment, 2);
            Grid.SetColumn(btnPreviewSegment, 6);


            //TODO：添加其它快捷工具条按钮

            //将答案项的解析文本中的某一片段移动到错项1的解析部分（解析部分以“　　解析＞＞”开头。
            var btnToErrorItemAnalys1 = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "移动到错项 1 的解析部分",
            };
            btnToErrorItemAnalys1.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/eiAnalys-1.png")),
            };
            btnToErrorItemAnalys1.MouseLeftButtonDown += BtnToErrorItemAnalys1_MouseLeftButtonDown;
            baseGrid.Children.Add(btnToErrorItemAnalys1);
            Grid.SetRow(btnToErrorItemAnalys1, 0);
            Grid.SetColumn(btnToErrorItemAnalys1, 0);

            var btnToErrorItemAnalys2 = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "移动到错项 2 的解析部分",
            };
            btnToErrorItemAnalys2.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/eiAnalys-2.png")),
            };
            btnToErrorItemAnalys2.MouseLeftButtonDown += BtnToErrorItemAnalys2_MouseLeftButtonDown;
            baseGrid.Children.Add(btnToErrorItemAnalys2);
            Grid.SetRow(btnToErrorItemAnalys2, 0);
            Grid.SetColumn(btnToErrorItemAnalys2, 1);

            var btnToErrorItemAnalys3 = new Border()
            {
                Style = btnStyle,
                Margin = new System.Windows.Thickness(1),
                Width = 24,
                Height = 24,
                BorderBrush = Brushes.Black,
                BorderThickness = new System.Windows.Thickness(1),
                ToolTip = "移动到错项 3 的解析部分",
            };
            btnToErrorItemAnalys3.Child = new Image()
            {
                Width = 16,
                Height = 16,
                Source = new BitmapImage(new Uri("pack://application:,,,/LunarMarkdownEditor;component/Images/eiAnalys-3.png")),
            };
            btnToErrorItemAnalys3.MouseLeftButtonDown += BtnToErrorItemAnalys3_MouseLeftButtonDown;
            baseGrid.Children.Add(btnToErrorItemAnalys3);
            Grid.SetRow(btnToErrorItemAnalys3, 0);
            Grid.SetColumn(btnToErrorItemAnalys3, 2);

            vPanel.Children.Add(baseGrid);
            this.Child = this.mainBorder = new Border()
            {
                Child = vPanel,
                BorderThickness = new System.Windows.Thickness(1),
                SnapsToDevicePixels = true,
                BorderBrush = Brushes.SaddleBrown,
            };

            LoadPythonScriptButtonGroups();

            this.MouseEnter += EditorPopupToolBar_MouseEnter;
        }

        private void BtnAddSquareMark_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Globals.MainWindow.WrapWithSquareRegionMark();
        }

        private void BtnJoinParagraphs_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            TextCommandManager.JoinLines(null);
        }

        public void LoadPythonScriptButtonGroups()
        {
            // 可以在这里添加多组按钮来调用脚本。
            // 每组按钮可以调用同一个脚本，允许调用时传递参数。
            if (scriptPanel == null)
            {
                scriptPanel = new StackPanel()
                {
                    Orientation = Orientation.Vertical,
                    Margin = new System.Windows.Thickness(1),
                    Background = new SolidColorBrush(Color.FromRgb(155, 123, 86)),
                };
                vPanel.Children.Add(scriptPanel);
            }

            scriptPanel.Children.Clear();
            hasScriptButtonGroup = false;

            foreach (var item in Globals.MainWindow.lbxWorkspacePythonScripts.Items)
            {
                var psli = item as PythonScriptListItem;
                if (psli == null || string.IsNullOrWhiteSpace(psli.PopupButtonGroupsText)) continue;
                var popText = psli.PopupButtonGroupsText.Replace("；", ";").Replace("｜", "|").Replace("，", ",").Replace("：", ":");
                var lines = popText.Split(new char[] { ';' });

                int brush_switcher = 0;
                foreach (var line in lines)
                {
                    // 每个 Line 格式如下：
                    //     组名①：按钮名1，参数1｜按钮名2，参数2
                    //     组名②：按钮名3，参数3｜按钮名4，参数4

                    var index = line.IndexOf(':');
                    if (index < 0)    // 允许忽略组名！！但冒号不可省略。
                        continue;
                    var groupName = line.Substring(0, index);
                    var buttonsText = line.Substring(index + 1);
                    var btnTxts = buttonsText.Split(new char[] { '|', });
                    var btnList = new List<PopupButton>();
                    foreach (var btnTxt in btnTxts)
                    {
                        if (string.IsNullOrWhiteSpace(btnTxt)) continue;
                        var indexS = btnTxt.IndexOf(',');
                        string btnContent;
                        string btnArgs;
                        if (indexS < 0)
                        {
                            btnContent = btnTxt;
                            btnArgs = btnTxt;
                        }
                        else
                        {
                            btnContent = btnTxt.Substring(0, indexS);
                            btnArgs = btnTxt.Substring(indexS + 1);
                            if (string.IsNullOrWhiteSpace(btnContent)) continue;
                            if (string.IsNullOrWhiteSpace(btnArgs))
                            {
                                btnArgs = btnContent;
                            }
                        }

                        var scriptPopButton = new PopupButton(groupName, btnContent, btnArgs, psli);
                        scriptPopButton.Click += ScriptPopButton_Click;
                        btnList.Add(scriptPopButton);

                        scriptPopButton.ContextMenu = new ContextMenu();
                        var cmi = new MenuItem()
                        {
                            Header = "编辑 " + psli.Title,
                            Style = TryFindResource("MetroMenuItem") as Style,
                            Tag = psli,
                        };
                        cmi.Click += Cmi_Click;
                        scriptPopButton.ContextMenu.Items.Add(cmi);
                    }

                    if (btnList.Count > 0)
                    {
                        brush_switcher++;

                        var wpGroup = new WrapPanel()
                        {
                            HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
                        };
                        scriptPanel.Children.Add(wpGroup);

                        if (string.IsNullOrWhiteSpace(groupName) == false)
                        {
                            //var tbGroup = new TextBlock()
                            //{
                            //    VerticalAlignment = System.Windows.VerticalAlignment.Center,
                            //    Padding = new System.Windows.Thickness(2, 1, 2, 1),
                            //    Foreground = Brushes.White,
                            //};

                            //var tbBorder = new Border()
                            //{
                            //    VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
                            //    Margin = new System.Windows.Thickness(2, 1, 1, 1),
                            //};

                            //tbBorder.Child = tbGroup;
                            //tbGroup.Text = groupName;

                            //wpGroup.Children.Add(tbBorder);

                            wpGroup.ToolTip = groupName;  // 还是改成都用图标吧。
                        }
                        else
                        {
                            wpGroup.ToolTip = "未命名组";
                        }

                        if (brush_switcher % 2 == 0)
                        {
                            wpGroup.Background = Brushes.LightGray;
                        }
                        else
                        {
                            wpGroup.Background = Brushes.Transparent;
                        }

                        foreach (var pbtn in btnList)
                        {
                            wpGroup.Children.Add(pbtn);
                        }

                        hasScriptButtonGroup = true;
                    }
                }
            }

            if (scriptPanel.Children.Count > 0)
            {
                scriptPanel.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                scriptPanel.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void Cmi_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var mi = sender as MenuItem;
            if (mi == null) return;

            var ownerItem = mi.Tag as PythonScriptListItem;
            if (ownerItem == null) return;

            ownerItem.EditScriptFile();
        }

        private void ScriptPopButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var senderButton = sender as PopupButton;
            if (senderButton == null) return;

            senderButton.MasterPythonScriptListItem?.RunScript(senderButton.GroupName, senderButton.Args);
        }

        private Grid baseGrid;

        public Grid BaseGrid { get { return baseGrid; } }

        private StackPanel scriptPanel = null;

        private RowDefinition questionToolsRowDefinition;

        private void BtnToErrorItemAnalys1_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            MoveToFstItemAnalys();
        }

        /// <summary>
        /// 将当前选中文本移动到找到的第一个错项的解析片段。
        /// </summary>
        public static void MoveToFstItemAnalys()
        {
            // 基本思路：寻找下一个“　　解析＞＞”的位置，然后插入。
            try
            {
                var edit = Globals.MainWindow.ActivedEditor;
                if (edit == null) return;
                if (edit.EditorBase.SelectionLength <= 0) return;

                var selOffset = edit.EditorBase.SelectionStart;
                var selLength = edit.EditorBase.SelectionLength;
                var selText = edit.EditorBase.SelectedText;
                if (selText.EndsWith("；"))
                    selText = selText.Substring(0, selText.Length - 1) + "。";

                var index1 = edit.EditorBase.Text.IndexOf("　　解析＞＞", edit.EditorBase.SelectionStart + edit.EditorBase.SelectionLength);
                if (index1 < 0) return;

                index1 += 6;
                edit.EditorBase.Select(index1, 0);
                edit.EditorBase.SelectedText = selText;
                edit.EditorBase.Select(selOffset, selLength);
                edit.EditorBase.SelectedText = "";
            }
            catch (Exception ex)
            {
                LMessageBox.Show(ex.Message, Globals.AppName, System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
            }
        }

        private void BtnToErrorItemAnalys2_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // 基本思路：寻找下两个“　　解析＞＞”的位置，然后插入。
            MoveToSecItemAnalys();
        }

        /// <summary>
        /// 将当前选中文本移动到找到的第二个错项的解析片段。
        /// </summary>
        public static void MoveToSecItemAnalys()
        {
            try
            {
                var edit = Globals.MainWindow.ActivedEditor;
                if (edit == null) return;
                if (edit.EditorBase.SelectionLength <= 0) return;

                var selOffset = edit.EditorBase.SelectionStart;
                var selLength = edit.EditorBase.SelectionLength;
                var selText = edit.EditorBase.SelectedText;
                if (selText.EndsWith("；"))
                    selText = selText.Substring(0, selText.Length - 1) + "。";

                var index1 = edit.EditorBase.Text.IndexOf("　　解析＞＞", edit.EditorBase.SelectionStart + edit.EditorBase.SelectionLength);
                if (index1 < 0) return;

                index1 += 6;

                var index2 = edit.EditorBase.Text.IndexOf("　　解析＞＞", index1);
                if (index2 < 0) return;

                index2 += 6;

                edit.EditorBase.Select(index2, 0);
                edit.EditorBase.SelectedText = selText;
                edit.EditorBase.Select(selOffset, selLength);
                edit.EditorBase.SelectedText = "";
            }
            catch (Exception ex)
            {
                LMessageBox.Show(ex.Message, Globals.AppName, System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
            }
        }

        private void BtnToErrorItemAnalys3_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // 基本思路：寻找下三个“　　解析＞＞”的位置，然后插入。
            MoveToTrdItemAnalys();
        }

        /// <summary>
        /// 将当前选中文本移动到找到的第三个错项的解析片段。
        /// </summary>
        public static void MoveToTrdItemAnalys()
        {
            try
            {
                var edit = Globals.MainWindow.ActivedEditor;
                if (edit == null) return;
                if (edit.EditorBase.SelectionLength <= 0) return;

                var selOffset = edit.EditorBase.SelectionStart;
                var selLength = edit.EditorBase.SelectionLength;
                var selText = edit.EditorBase.SelectedText;
                if (selText.EndsWith("；"))
                    selText = selText.Substring(0, selText.Length - 1) + "。";

                var index1 = edit.EditorBase.Text.IndexOf("　　解析＞＞", edit.EditorBase.SelectionStart + edit.EditorBase.SelectionLength);
                if (index1 < 0) return;

                index1 += 6;

                var index2 = edit.EditorBase.Text.IndexOf("　　解析＞＞", index1);
                if (index2 < 0) return;

                index2 += 6;

                var index3 = edit.EditorBase.Text.IndexOf("　　解析＞＞", index2);
                if (index3 < 0) return;

                index3 += 6;

                edit.EditorBase.Select(index3, 0);
                edit.EditorBase.SelectedText = selText;
                edit.EditorBase.Select(selOffset, selLength);
                edit.EditorBase.SelectedText = "";
            }
            catch (Exception ex)
            {
                LMessageBox.Show(ex.Message, Globals.AppName, System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
            }
        }

        private void BtnHaiCi_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var activeEdit = Globals.MainWindow.ActivedEditor;
            if (activeEdit == null) return;

            var selectedText = activeEdit.EditorBase.SelectedText;
            if (string.IsNullOrEmpty(selectedText))
            {
                LMessageBox.Show("请先在编辑区选中要搜索的单词！", Globals.AppName, System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return;
            }

            //var sw = Globals.MainWindow.SearchWindow;
            //if (sw.Visibility != System.Windows.Visibility.Visible) sw.Show();
            //if (sw.WindowState == System.Windows.WindowState.Minimized) sw.WindowState = System.Windows.WindowState.Normal;
            //if (sw.IsActive == false) sw.Activate();

            ////sw.webBrowser.Source = new Uri(string.Format("http://www.youdao.com/w/eng/{0}/#keyfrom=dict2.index", selectedText));
            ////调用海词词典搜索在选择区选中的文本。原来用有道，老提示网页出错。
            //sw.webBrowser.Source = new Uri(string.Format("http://dict.cn/{0}", selectedText));

            //默认情况下，WPF使用的IE内核版本较旧，打开一些网页时老出问题，不如直接调用系统默认浏览器。
            try
            {
                System.Diagnostics.Process.Start(string.Format("http://dict.cn/{0}", selectedText));
            }
            catch (Exception ex)
            {
                LMessageBox.ShowWarning(ex.Message + "\r\n" + "　　可能 Windows 操作系统对 https 协议的应用程序关联出了点小问题。");
            }
        }

        private void BtnBaidu_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var activeEdit = Globals.MainWindow.ActivedEditor;
            if (activeEdit == null) return;

            var selectedText = activeEdit.EditorBase.SelectedText;
            if (string.IsNullOrEmpty(selectedText))
            {
                LMessageBox.Show("请先在编辑区选中要搜索的文本！", Globals.AppName, System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return;
            }

            //调用百度搜索在选择区选中的文本
            //var sw = Globals.MainWindow.SearchWindow;
            //if (sw.Visibility != System.Windows.Visibility.Visible) sw.Show();
            //if (sw.WindowState == System.Windows.WindowState.Minimized) sw.WindowState = System.Windows.WindowState.Normal;
            //if (sw.IsActive == false) sw.Activate();

            //sw.webBrowser.Source = new Uri(string.Format("https://www.baidu.com/s?wd={0}", selectedText));

            //默认情况下，WPF使用的IE内核版本较旧，打开一些网页时老出问题，不如直接调用系统默认浏览器。
            try
            {
                System.Diagnostics.Process.Start(string.Format("https://www.baidu.com/s?wd={0}", selectedText));
            }
            catch (Exception ex)
            {
                LMessageBox.ShowWarning(ex.Message + "\r\n" + "　　可能 Windows 操作系统对 https 协议的应用程序关联出了点小问题。");
            }
        }

        private void BtnPaster_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (masterEditorBase != null) masterEditorBase.Paste();
        }

        private void BtnCopy_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (masterEditorBase != null) masterEditorBase.Copy();
        }

        private void BtnCut_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (masterEditorBase != null) masterEditorBase.Cut();
        }

        private void BtnAddRegionMark_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Globals.MainWindow.WrapWithRegionMark();
        }

        private void BtnPreviewSegment_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // if (this.masterEditorBase == null || this.masterEditorBase.SelectionLength == 0) return;
            // 这个功能可以只选中某行中的某个位置就预览整行。所以这里不需要这个判断。

            Globals.MainWindow.PreviewMarkdownSegment();
        }

        private Border mainBorder;

        public Border MainBorder { get { return this.mainBorder; } }

        private void EditorPopupToolBar_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            this.MainBorder.Opacity = 1;
            this.entered = true;
        }

        private void BtnCodeSpinnet_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (this.masterEditorBase == null || this.masterEditorBase.SelectionLength == 0) return;

            this.masterEditorBase.SwitchCodeSnippet();
        }

        private void BtnAddBlockQuoteMark_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (this.masterEditorBase == null || this.masterEditorBase.SelectionLength == 0) return;

            this.masterEditorBase.AddBlockQuoterMarksToSelectedLines();
        }

        private void BtnUnorderedList_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (this.masterEditorBase == null || this.masterEditorBase.SelectionLength == 0) return;

            this.masterEditorBase.SwitchListMark(true);
        }

        private void BtnItalic_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (this.masterEditorBase == null || this.masterEditorBase.SelectionLength == 0) return;

            this.masterEditorBase.SwitchItalic();
        }

        private void BtnBold_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (this.masterEditorBase == null || this.masterEditorBase.SelectionLength == 0) return;

            this.masterEditorBase.SwitchBold();
        }

        private bool entered = false;
        /// <summary>
        /// 鼠标指针是否已进入。
        /// </summary>
        public bool Entered
        {
            get { return this.entered; }
            set { this.entered = value; }
        }

        private StackPanel vPanel = new StackPanel() { Orientation = Orientation.Vertical, Background = Brushes.White, };

        public StackPanel VPanel { get { return vPanel; } }

        public bool IsQuestionToolsBarShow
        {
            set
            {
                if (questionToolsRowDefinition == null) return;
                if (value)
                {
                    questionToolsRowDefinition.Height = new System.Windows.GridLength(1, System.Windows.GridUnitType.Auto);
                }
                else questionToolsRowDefinition.Height = new System.Windows.GridLength(0, System.Windows.GridUnitType.Pixel);
            }
        }

        private bool hasScriptButtonGroup = false;
        public bool HasScriptButtonGroup { get { return hasScriptButtonGroup; } }

        private MarkdownEditorBase masterEditorBase;
    }
}
